import React, { useEffect, useRef, useState } from 'react'
import { Button, Modal, message, Spin } from 'antd'
import { useNavigate } from 'react-router-dom'
import { faceService } from '../../services/face'

function Index() {
  const navigate = useNavigate()
  const [open, setOpen] = useState(false)
  const [busy, setBusy] = useState(false)
  const videoRef = useRef<HTMLVideoElement | null>(null)
  const streamRef = useRef<MediaStream | null>(null)

  useEffect(() => {
    if (!open) return
    const start = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480 }, audio: false })
        streamRef.current = stream
        if (videoRef.current) {
          videoRef.current.srcObject = stream
          await videoRef.current.play()
        }
      } catch {
        message.error('无法访问摄像头，请检查浏览器权限')
        setOpen(false)
      }
    }
    start()
    return () => {
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(t => t.stop())
        streamRef.current = null
      }
    }
  }, [open])

  const captureBase64 = (): string => {
    const video = videoRef.current!
    const canvas = document.createElement('canvas')
    canvas.width = video.videoWidth || 640
    canvas.height = video.videoHeight || 480
    const ctx = canvas.getContext('2d')!
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
    const dataUrl = canvas.toDataURL('image/jpeg', 0.92)
    return dataUrl.replace(/^data:image\/\w+;base64,/, '')
  }

  const handleFaceRegister = async () => {
    setBusy(true)
    try {
      const base64 = captureBase64()
      message.loading({ content: '获取授权...', key: 'reg', duration: 0 })
      const token = await faceService.getAccessToken()
      message.loading({ content: '进行活体与质量检测...', key: 'reg', duration: 0 })
      await faceService.detectFace(base64, token)
      message.loading({ content: '写入人脸库...', key: 'reg', duration: 0 })
      // 使用时间戳作为示例 userId，实际可以用手机号等
      const userId = 'face_user_' + Date.now()
      await faceService.addUserToFaceset(base64, token, userId)
      message.success({ content: '注册成功，已录入人脸', key: 'reg' })
      setOpen(false)
      navigate('/login')
    } catch (e: unknown) {
      const err = (e as { response?: { data?: { error_msg?: string } }, message?: string })?.response?.data?.error_msg || (e as { message?: string })?.message || '注册失败，请重试'
      message.error({ content: err, key: 'reg' })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div style={{ minHeight: '100vh', background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ width: 420, background: '#fff', padding: 24, borderRadius: 8, boxShadow: '0 6px 24px rgba(0,0,0,0.06)' }}>
        <h2 style={{ marginBottom: 8 }}>人脸识别注册</h2>
        <p style={{ color: '#666', marginBottom: 24 }}>点击下方按钮，打开摄像头并将人脸入库</p>
        <Button type="primary" block onClick={() => setOpen(true)}>人脸识别注册</Button>
        <Button style={{ marginTop: 12 }} block onClick={() => navigate('/login')}>返回登录</Button>
      </div>

      <Modal open={open} onCancel={() => !busy && setOpen(false)} footer={null} title="人脸识别注册" width={720}>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          <video ref={videoRef} style={{ width: 640, height: 480, background: '#000', borderRadius: 6 }} />
          {busy && <Spin />}
        </div>
        <div style={{ marginTop: 16, display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
          <Button onClick={() => setOpen(false)} disabled={busy}>取消</Button>
          <Button type="primary" onClick={handleFaceRegister} loading={busy}>开始注册</Button>
        </div>
      </Modal>
    </div>
  )
}

export default Index

